package com.kcs.fxmargin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.action.form.LoginActionForm;
import com.kcs.fxmargin.bo.CustomerInformationBO;
import com.kcs.fxmargin.model.MCustInfo;
import com.kcs.fxmargin.service.CommonService;
import com.kcs.fxmargin.service.CustInfoService;

/**
 * Servlet implementation class SetupCustomerInformationServlet
 */
public class SetupCustomerInformationServlet extends HttpServlet {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=utf-8";	
	private CustInfoService service = new CustInfoService();
    private CommonService common = new CommonService();
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SetupCustomerInformationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		
		response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        response.setContentType(CONTENT_TYPE);
        
        System.out.println("SetupCustomerInformationServlet : Start");
        
        LoginActionForm loginBean = null;
        boolean isDuplicateCifno = true;
        
        try {
        	HttpSession session = request.getSession();
        	
        	if(session == null) {
        		JSONObject json = new JSONObject();
                json.put("data", "to");
                json.write(out);
        	} else {
        		loginBean = (LoginActionForm) request.getSession().getAttribute(Constant.LOGIN_DATA_SESSION);
    			
            	String id					= request.getParameter("id");
            	String cifNo 				= request.getParameter("cifNo");
            	String customerName 		= request.getParameter("customerName");
            	String marginAccNo	  		= request.getParameter("marginAccNo");
            	String marginAccName 		= request.getParameter("marginAccName");
            	String depositAccNo 		= request.getParameter("depositAccNo");
            	String depositAccName	  	= request.getParameter("depositAccName");
            	String customerLimitAmount 	= request.getParameter("customerLimitAmount");
            	String updateDate 			= request.getParameter("updateDate");
            	String customerStatus		= request.getParameter("customerStatus");
            	String action	  			= request.getParameter("action");
            	String userId				= "";
            	int rowVers					= Integer.parseInt(request.getParameter("rowVersion"));
            	String result				= "";
            	
            	if(loginBean != null) {
            		userId = loginBean.getUserId();
            	}
            	
            	System.out.println("id		 			= " + id);
            	System.out.println("cifNo 				= " + cifNo);
            	System.out.println("customerName 		= " + customerName);
            	System.out.println("marginAccNo 	 	= " + marginAccNo);
            	System.out.println("marginAccName 		= " + marginAccName);
            	System.out.println("depositAccNo 		= " + depositAccNo);
            	System.out.println("depositAccName 	 	= " + depositAccName);
            	System.out.println("customerLimitAmount = " + customerLimitAmount);
            	System.out.println("updateDate 			= " + updateDate);
            	System.out.println("updateBy 	 		= " + userId);
            	System.out.println("customerStatus 	 	= " + customerStatus);
            	System.out.println("rowVersion 			= " + rowVers);		
            	System.out.println("action 	 			= " + action);
            		
            	MCustInfo custInfo = new MCustInfo();
            	
            	custInfo.setId(id);
            	custInfo.setCifNo(cifNo);
            	custInfo.setCustName(customerName);
            	custInfo.setMarginAccNo(marginAccNo);
            	custInfo.setMarginAccName(marginAccName);
            	custInfo.setDepositAccNo(depositAccNo);
            	custInfo.setDepositAccName(depositAccName);
            	custInfo.setCustLimitAmt(convertStringtoBigDecimal(customerLimitAmount));
            	custInfo.setCustStatusCode(customerStatus);
            	custInfo.setActiveStatus("A");
            	custInfo.setRowVersion(rowVers);
            	custInfo.setCreateby(userId);
            	custInfo.setUpdateBy(userId);
            	
            	if("insert".equals(action)){
            		//-- Check Duplicate CifNo
                	isDuplicateCifno = checkDuplicateCifNo(cifNo);
                	//------
                	
                	if(!isDuplicateCifno){
                		result = service.insertCustInfo(custInfo);
                	}else{
                		result = "duplicateCifNo";
                	}
            	
            	
            	}else if ("update".equals(action)){
            		
            		int rowVersion = common.getRowVersion(Constant.CUST_INFO, custInfo.getId());
            		
            		if(rowVersion <= custInfo.getRowVersion()){
            			custInfo.setRowVersion(rowVersion + 1);
            			result = service.updateCustInfo(custInfo);
            		}else{
            			log.error("Concurrent Data Access." + Constant.CUST_INFO + " [id = " + custInfo.getId() + "]");
            			result = "Dup";
            		}
            		
            	}
            	
            	JSONObject json = new JSONObject();
                json.put("data", result);
                json.write(out);
                
                System.out.println("result : "+result);
        	}
        	
        	
        } catch (Exception e) {
        	log.error(e);
            out.print("{\"status\": \"failed\", \"message\": \"" +
                      e.getMessage() + "\"}");
        } finally {
            out.close();
        }

        
        System.out.println("SetupCustomerInformationServlet : End");
		
	}
	
	private BigDecimal convertStringtoBigDecimal(String number) throws Exception {
		BigDecimal bigDecimal = new BigDecimal(0);
		
		if(number != null && !"".equals(number)) bigDecimal = new BigDecimal(number);
		
		return bigDecimal;
	}
	
	private boolean checkDuplicateCifNo(String cifNo)throws Exception{
		CustInfoService svc = null;
		List<CustomerInformationBO>	resultList = null;
		MCustInfo custInfo = null;
		boolean result = true;
		
		try{
			svc = new CustInfoService();
			custInfo = new MCustInfo();
			
			custInfo.setCifNo(cifNo);
			
			resultList = svc.searchPopupCustomer(custInfo);
			
			if(resultList == null || resultList.size() == 0){
				result = false;
			}
			
		}catch(Exception e){
			throw e;
		}
		
		return result;
	}

}
